package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.entity.MerchantApp;
import com.qianniu.napi.admin.entity.Order;
import com.qianniu.napi.admin.entity.OrderRefund;
import com.qianniu.napi.admin.entity.penum.RefundEnum;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 订单退款
 * </p>
 *
 * @author chenxuebin
 * @since 2018-08-22
 */
@Controller
public class OrderRefundController {

    private static final Logger logger = LoggerFactory.getLogger(OrderRefundController.class);

    @Autowired
    private IOrderRefundService orderRefundService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IMerchantAppService merchantAppService;
    @Autowired
    private IQnpay qnpay;
    @Autowired
    private IRedisService redisService;

    @RequestMapping("admin/orderrefund/index")
    public String index() {
        return "admin/orderrefund";
    }

    @RequestMapping("/admin/orderrefund/list")
    @ResponseBody
    public Page<OrderRefund> alist(@RequestParam(value = "offset", required = false) Integer offset,
                                   @RequestParam(value = "status", required = false) Integer status,
                                   @RequestParam(value = "search", required = false) String search,
                                   @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<OrderRefund> wrapper = new EntityWrapper<OrderRefund>();
        int utype = ObjectUtil.getUserType();
        if (utype < 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());
        wrapper.eq("state", 1);
        if (status != 99) wrapper.eq("status", status);
        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().like("order_no", search).or().like("refund_no", search).or().like("goods_name", search);

        wrapper.orderBy("id", false);
        Page<OrderRefund> page = orderRefundService.selectPage(new Page<OrderRefund>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/orderrefund/add")
    public String add(@Valid OrderRefund bean, BindingResult bindingResult) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setUid(ObjectUtil.getUid());
        bean.insert();
        return "admin/orderrefund";
    }

    @RequestMapping("/admin/orderrefund/getOrderRefundById")
    @ResponseBody
    public OrderRefund getOrderRefundById(long id) {
        OrderRefund orderrefund = orderRefundService.selectById(id);
        return orderrefund;
    }

    @RequestMapping("/admin/orderrefund/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = orderRefundService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/orderrefund/changeStatus")
    @ResponseBody
    public Jinfo changeStatus(long id, int status) {
        Jinfo jinfo = new Jinfo();

        OrderRefund or = orderRefundService.selectById(id);
        if (or != null) {
            or.setApplynum(or.getApplynum() + 1);
            or.setModifier(ObjectUtil.getUid());
            or.setModifytime(new Date());
            or.updateById();
        }

        if (status == RefundEnum.success.getVal()) {
            Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", or.getOrderNo()));
            MerchantApp ma = merchantAppService.selectById(order.getMpid());
            Map map = qnpay.cancelOrder(order, ma.getAppid());
            if (map.containsKey("code")) {
                jinfo.setCode(Integer.valueOf(map.get("code").toString()));
            }
        }
        return jinfo;
    }

    @RequestMapping("/admin/orderrefund/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        OrderRefund bean = new OrderRefund();
        bean.setId(id);
//        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        orderRefundService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/orderrefund/modify")
    public String update(OrderRefund bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = orderRefundService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

}
